package org.quarenden.demo.sequence;

import org.hibernate.annotations.Source;
import org.quarenden.demo.util.MachineIdentifierUtil;
import org.quarenden.demo.util.ServiceInfoUtil;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author liboyi
 */
public class GlobalSequenceIdProvider {

    //业务主键才通过此方式获取
    private static final SequenceId seq1;

    private static final SequenceId seq2;

    static {
        JdbcSequenceIdProvider jdbcSequenceIdProvider = new JdbcSequenceIdProvider();
        seq1 = jdbcSequenceIdProvider.create("seq1");
        seq2 = jdbcSequenceIdProvider.create("seq2");
    }

    public static String seq1NextVal() {
        return new StringBuilder("").append(MachineIdentifierUtil.createMachineIdentifier()).append(ServiceInfoUtil.getPort()).append(autoGenericCode(seq1.nextVal().toString(),8)).toString();
    }

    public static String seq2NextVal() {
        return new StringBuilder("").append(MachineIdentifierUtil.createMachineIdentifier()).append(ServiceInfoUtil.getPort()).append(autoGenericCode(seq2.nextVal().toString(),8)).toString();
    }

    /**
     * 不够位数的在前面补0，保留num的长度位数字
     * @param code
     * @return
     */
    private static String autoGenericCode(String code, int num) {
        String result = "";
        // 保留num的位数
        // 0 代表前面补充0
        // num 代表长度为4
        // d 代表参数为正数型
        result = String.format("%0" + num + "d", Integer.parseInt(code) + 1);

        return result;
    }

}
